$.fn.datagrid = function (opt,row) {
    var defaultPageNum = 1;
    if( opt == 'reload' ){
        reloadData($(this),defaultPageNum,row);
        return;
    }else if( opt == 'addRow' ){
        addRow($(this),row);
        return;
    }else if( opt == 'addRows' ){
        for( var i=0 ; i<row.length ; i++ ){
            addRow($(this),row[i]);
        }
        return;
    }else if( opt == 'getSelections' ){
        var selections = [];
        $('#table .vui-table-cell input[type="checkbox"]').each(function () {
            if( $(this).prop("checked") ){
                selections.push($(this).parent().data());
            }
        });
        return selections;
    }
    var options = {
        page:1,limit:10,pagination:true,limits:[10,20,30,50,100],queryParams:{}
    };
    $.extend(options,opt);

    var grid = $(this);
    grid.data(options);

    var table = createTable(grid,options);

    createHead(options,table);
    if( options.url ){
        if( options.unload ){
            createBody(options,{"code":0,"total":"0","rows":[]},table,defaultPageNum);
        }else{
            loadUrl(options,function (data) {
                createBody(options,data,table,defaultPageNum);
            });
        }
    }else if( options.data ){
        createBody(options,options.data,table,defaultPageNum);
    }

};

function reloadData(_this,defaultPageNum,queryParams) {
    var options = _this.data();
    if(queryParams)$.extend(options.queryParams,queryParams);
    var table = _this.find('div[role="table"]');
    loadUrl(options,function (data) {
        createBody(options,data,table,defaultPageNum);
    });
}

function getDisplayPages(totalPage,currPageNum) {
    var pages = [];
    if( totalPage > 9 ){
        if( currPageNum < 5 ){
            pages = [1,2,3,4,5,'...',totalPage];
        }else if( currPageNum > totalPage - 4  ){
            pages = [1,'...',totalPage-4,totalPage-3,totalPage-2,totalPage-1,totalPage];
        }else{
            pages = [1,'...',currPageNum-2,currPageNum-1,currPageNum,currPageNum+1,currPageNum+2,'...',totalPage];
        }
    }else{
        for(var i=1 ; i<=totalPage ; i++  ){
            pages.push(i);
        }
    }
    return pages;
}

function createPageByDis(options,total,table,currPageNum,dis) {
    if( dis == currPageNum ){
        return $('<span class="vui-page-curr">'+dis+'</span>');
    }else if( dis == '...' ){
        return $('<span class="vui-page-spr">…</span>');
    }else{
        var page = $('<a href="javascript:;" data-page="'+dis+'">'+dis+'</a>');
        page.click(function () {
            options.page = $(this).data('page');
            loadUrl(options,function (data) {
                createBody(options,data,table,options.page);
            });
        });
        return page;
    }
}

function createPage(options,total,table,currPageNum) {
    table.parent().find('.vui-page').remove();

    var page = $('<div class="vui-page"></div>');
    page.append('<span class="vui-page-count">共 '+total+' 条</span>');
    page.append(getPagePre(options,total,table,currPageNum));

    var totalPage = total % options.limit ==0 ? total/options.limit : Math.floor(total/options.limit)+1 ;
    if(!options.simplePagination){
        //
        var disPages = getDisplayPages(totalPage,currPageNum);
        for( var i=0 ; i<disPages.length ; i++ ){
            page.append(createPageByDis(options,total,table,currPageNum,disPages[i]));
        }
        //
    }
    page.append(getPageNext(options,total,table,currPageNum,totalPage));
    if(!options.simplePagination){
        page.append(getPageLimits(options,total,table,currPageNum));
    }
    page.append(getPageSkip(options,total,table,currPageNum));

    table.parent().append(page);
}

function getPageSkip(options,total,table,currPageNum) {
    var skip = $('<span class="vui-page-skip">到第<input type="text" value="'+currPageNum+'"/>页</span>');
    var button = $('<button type="button">确定</button>');
    skip.append(button);
    button.click(function () {
        options.page = $(this).parent().find('input').val();
        loadUrl(options,function (data) {
            createBody(options,data,table,options.page);
        });
    });
    skip.find('input').click(function () {
        $(this).select();
    });
    return skip;
}

function getPageLimits(options,total,table,currPageNum) {
    var limit = $('<span class="vui-page-limit"></span>');
    var select = $('<select></select>');
    for( var i=0 ; i<options.limits.length ; i++ ){
        var limitsNum = options.limits[i];
        var option = $('<option value="'+limitsNum+'">'+limitsNum+' 条/页</option>');
        if( options.limit == limitsNum ){
            option.attr("selected","selected");
        }
        select.append(option);
    }
    select.change(function () {
        var limitValue = $(this).find('option:selected').val();
        options.page = currPageNum;
        options.limit = limitValue;
        loadUrl(options,function (data) {
            createBody(options,data,table,options.page);
        });
    });
    limit.append(select);
    return limit;
}

function getPagePre(options,total,table,currPageNum) {
    var pre = $('<a href="javascript:;" class="vui-page-prev" data-page="'+(currPageNum-1)+'">上一页</a>');
    if( currPageNum == 1 ){
        pre.addClass("vui-page-disabled");
    }else{
        pre.click(function () {
            options.page = $(this).data('page');
            loadUrl(options,function (data) {
                createBody(options,data,table,options.page);
            });
        });
    }
    return pre;
}

function getPageNext(options,total,table,currPageNum,totalPage) {
    var next = $('<a href="javascript:;" class="vui-page-next" data-page="'+(currPageNum+1)+'">下一页</a>');
    if( currPageNum == totalPage ){
        next.addClass("vui-page-disabled");
    }else{
        next.click(function () {
            options.page = $(this).data('page');
            loadUrl(options,function (data) {
                createBody(options,data,table,options.page);
            });
        });
    }
    return next;
}

function loadUrl(options,callback) {
    options.queryParams.page = options.page;
    options.queryParams.limit = options.limit;
    
    var data =$.extend(options.queryParams,{loginUserId:top.loginUserId,customerId:top.customerId,loginCompanyId:top.loginCompanyId,loginCompanyLogicalCode:top.loginCompanyLogicalCode});
    
    $.ajax({
        url:options.url,
        data:data,
        type:'POST',
        dataType:'json',
        success:function(resp){
            if( resp.result == 2 ){
                top.layer.confirm('无权限或者登陆过期，即将跳转到登陆界面', {icon: 3, title:'提示'}, function(index){
                    top.app.toLogin();
                    top.layer.close(index);
                });
            }else{
                callback(resp);
            }
        }
    });
}

function createTable(grid,options) {
    grid.css({"padding":"10px"});
    grid.append('<div role="table" class="vui-table"></div>');
    if( options.width )grid.width(options.width);
    return grid.find('div[role="table"]');
}

function createBody(options,data,table,currPageNum) {
    table.find('.vui-table-row').remove();

    var rows = data.rows;
    var columns = options.columns;

    for( var i=0 ; i<rows.length ; i++ ){
        createRow(rows[i],columns,table,options);
    }

    if( options.loadSuccess ){
        options.loadSuccess();
    }

    if(options.pagination){
        createPage(options,data.total,table,currPageNum);
    }

    if( options.statistics ){
        createStatistics(options,data,table);
    }

    resetTable(table);

}

function createStatistics(options,data,table) {
    var row = {};
    for( var i=0 ; i<options.columns.length ; i++ ){
        var column = options.columns[i];
        if( column.count ){
            row[column.field] = getStatisticsValue(data,column);
        }else{
            row[column.field] = '';
        }
    }
    for( var i=0 ; i<options.columns.length ; i++ ){
        var column = options.columns[i];
        if( column.rowFormatter ){
            row[column.field] = column.rowFormatter(row);
        }
    }
    createStatisticsRow(row,options.columns,table);
}

function getStatisticsValue(data,column) {
    var sum = 0,rows = data.rows;
    for( var i=0 ; i<rows.length ; i++ ){
        var value = getValue(rows[i],column);
        if( value ) sum = app.add(sum,value);
    }

    if( column.count == 'avg' && rows.length > 0){
        sum = app.div(sum,rows.length);
    }

    //sum = app.div(sum,100);

    if( column.n == 'number' ) sum = (sum+'').replace('.00','');
    return sum;
}

function resetTable(table) {
    var tableWidth = table.width();
    var tableOutWidth = table.parent().width();
    if( tableWidth > tableOutWidth ){
        table.css({"width":"auto"});
    }
}

function addRow(grid,row) {
    var options = grid.data();
    var table = grid.find('div[role="table"]');
    createRow(row,options.columns,table,options);
}

function createStatisticsRow(row,columns,table) {
    var _row = $('<div statistics="1" class="vui-table-row"></div>');
    _row.data(row);
    for( var j=0 ; j<columns.length ; j++ ){
        var column = columns[j];
        var cell = $('<div class="vui-table-cell"><strong style="font-weight: bold;">'+row[column.field]+'</strong></div>');
        cell.data(column);
        cell.attr('field',column.field);

        var cellCss = {"text-align":column.align};
        cellCss["padding-"+column.align] = "15px";
        if(column.align)cell.css(cellCss);
        if( column.n == 'number' || column.n == 'money' ){
            cell.css({"text-align":"right","padding-right":"10px"});
        }
        _row.append(cell);
    }
    table.append(_row);
}

function createRow(row,columns,table,options) {
    var _row = $('<div class="vui-table-row"></div>');
    _row.data(row);

    if( options.checkbox ){
        var ck = $('<input type="checkbox" value="'+row.id+'"/>');
        ck.click(function (e) {
            e.stopPropagation();
        });
        var cell = $('<div class="vui-table-cell"></div>');
        cell.append(ck);
        cell.data(row);
        _row.append(cell);
    }

    _row.click(function () {
        if( options.checkOnClick ){
            var ck = _row.find('input[type="checkbox"]');
            ck.prop("checked",!ck.prop('checked'));

        }
    });

    for( var j=0 ; j<columns.length ; j++ ){
        var column = columns[j];
        var cell = $('<div class="vui-table-cell"></div>');
        cell.data(column);
        cell.attr('editor',column.editor?column.editor:'');
        cell.attr('field',column.field);
        if(column.align)cell.css({"text-align":column.align,"padding-left":"15px"});
        appendValue(cell,getValue(row,column));
        cell.click(cellClickEvent);
        if( column.n == 'number' || column.n == 'money' ){
            cell.css({"text-align":"right","padding-right":"10px"});
        }
        _row.append(cell);
    }

    table.append(_row);
}

function appendValue(cell,value) {
    if( value[0] == app.DEFAULT_ALL_VALUE ){
        for( var i=1 ; i<value.length ; i++ ){
            cell.append(value[i]);
        }
    }else{
        cell.append(value);
    }
}

function getValue(row,column) {
    var value;
    if( column.formatter ){
        value = column.formatter(row,row[column.field]);
    }else{
        value = row[column.field];
    }
    if(value){
        if( column.n == 'number' )value = (app.div(value,app.DIV)+'').replace('.00','');
        if( column.n == 'money' )value = (app.div(value,app.DIV)+'');
        if( column.n == 'date' )value = app.time2str(value);
    }

    if( value == undefined || value==null){
        return '';
    }
    return value;
}

function cellClickEvent(e) {
    var editor = $(this).attr('editor');
    var column = $(this).data();
    if( editor == 'text' || editor == 'decimal' ){
        createInputEditor($(this),column);
    }else if( editor == 'combobox' ){
        createComboEditor($(this),column);
        e.stopPropagation();
    }
}

function createInputEditor(_this,column) {
    var editor = column.editor;
    if( _this.find('.input-edit').length > 0 ){
        return null;
    }

    var input = $('<input type="text" e="1" class="input-edit"/>');
    var value = $.trim(_this.html());
    input.width(_this.width()-2).val(value).data({"editor":editor,"value":value});

    input.blur(function(){
        inputEditorEvent($(this));
    }).keydown(function(e){
        if( e.keyCode == 13 )inputEditorEvent($(this));
    });
    _this.empty().append(input);
    input.focus().select();
}

function inputEditorEvent(_this) {
    var editor = _this.data("editor");
    var value = _this.val();

    if( editor == 'decimal' ){
        var reg = /^(-?\d+)(\.\d{0,2})?$/;
        if( !reg.test(value) ){
            value = _this.data("value");
        }
        value = value?parseFloat(value).toFixed(2):'';
    }
    
    var cellEle = _this.parent();
    cellEle.html(value);
    var column = cellEle.data() ;
    if( column.end ) {
        var row = cellEle.parent().data();
        column.end(row,value,cellEle);
    }
}

function createComboEditor(_this,column) {
    if( _this.find('input').length > 0 ){
        return;
    }
    var id = 'combo'+ new Date().getTime();
    var combo = $('<div role="combobox" id="'+id+'"></div>');
    _this.empty().append(combo);
    $('#'+id).combobox({
        width:_this.width(),
        data:column.comboData,
        name:id,
        valueField:'id',
        textField:'name'
    });

    if(column.comboboxData){
        var comboboxData = column.comboboxData(_this);
        if( comboboxData && comboboxData.value ){
            $('#'+id).combobox('setValue',comboboxData.value,comboboxData.text);
        }
    }
}

function createHead(options,table) {
    var columns = options.columns;
    var head = $('<div class="vui-table-head"></div>');

    if( options.checkbox ){
        head.append('<div class="vui-table-cell" style="width:20px;"></div>');
    }

    var columnWidthSum = getAllColumnWidthSum(columns);
    if( options.width && columnWidthSum > options.width ){
        for( var i=0 ; i<columns.length ; i++ ){
            var column = columns[i];
            columns[i].width = app.mul(app.div(column.width,columnWidthSum),options.width);
        }
    }

    for( var i=0 ; i<columns.length ; i++ ){
        var column = columns[i];
        var cell = $('<div class="vui-table-cell">'+column.title+'</div>');
        if( column.width )cell.width(column.width);
        head.append(cell);
    }

    table.append(head);
}

function getAllColumnWidthSum(columns) {
    var sum = 0;
    for( var i=0 ; i<columns.length ; i++ ){
        sum += columns[i].width;
    }
    return sum;
}